package com.example.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.example.common.constant.RedisConstant;
import com.example.common.exception.BizCodeEnum;
import com.example.common.utils.DomainNameUtils;
import com.example.common.utils.R;
import com.example.common.vo.MemberResponseVo;
import com.example.gulimall.auth.feign.MemberFeignService;
import com.example.gulimall.auth.feign.ThirdPartFeignService;
import com.example.gulimall.auth.vo.UserLoginVo;
import com.example.gulimall.auth.vo.UserRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 登陆
 * @author GuLin
 * @date 2021-06-29 16:58
 */
@Slf4j
@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 发送验证码
     * @author GuLin
     * @date 19:26 2021/6/29
     * @param phone
     * @return com.example.common.utils.R
     **/
    @ResponseBody
    @GetMapping(value = "/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //接口防刷
        String value = stringRedisTemplate.opsForValue().get(RedisConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(StringUtils.isNotBlank(value)){
           Long smsTime = Long.parseLong(value.split("_")[1]);
           //小于60秒
           if(System.currentTimeMillis() - smsTime < 60000){
               return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
           }
        }
        //生成验证码
        String code = UUID.randomUUID().toString().substring(0,6);
        String redis_code = code + "_" + System.currentTimeMillis();
        //缓存验证码
        stringRedisTemplate.opsForValue().set(RedisConstant.SMS_CODE_CACHE_PREFIX+phone,redis_code,10, TimeUnit.MINUTES);
        try {
            thirdPartFeignService.sendCode(phone,code);
        } catch (Exception e) {
            log.error("远程调用发送验证码异常,{}",e.getMessage());
        }
        return R.ok();
    }

    /**
     * 用户注册
     * @author GuLin
     * @date 19:27 2021/6/29
     * @param vos 注册信息
     * @param result JSR303异常信息
     * @param attributes  可以通过session保存信息并在重定向的时候携带过去
     * @return java.lang.String
     **/
    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo vos, BindingResult result, RedirectAttributes attributes) {
        //1.判断校验是否通过
        Map<String, String> errors = new HashMap<>();
        if(result.hasErrors()){
            //1.1 如果校验不通过，则封装校验结果
            result.getFieldErrors().forEach(item->{
                errors.put(item.getField(),item.getDefaultMessage());
                //将错误信息封装到session中
                 attributes.addFlashAttribute("errors",errors);
            });
            //重定向到注册页
            return "redirect:"+DomainNameUtils.auth+"/reg.html";
        } else {
            //判断验证码是否正确
            String value = stringRedisTemplate.opsForValue().get(RedisConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
            if(StringUtils.isNotBlank(value) && vos.getCode().equals(value.split("_")[0])){
               //删除验证码
                stringRedisTemplate.delete(RedisConstant.SMS_CODE_CACHE_PREFIX+vos.getPhone());
                //远程调用会员服务注册
                R r = memberFeignService.register(vos);
                if(r.getCode() == 0){
                    //调用成功，重定向登录页
                    return "redirect:"+DomainNameUtils.auth+"/login.html";
                } else {
                    //调用失败，返回注册页并显示错误信息
                    String msg = (String) r.get("msg");
                    errors.put("msg", msg);
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:"+DomainNameUtils.auth+"/reg.html";
                }
            } else {
                //2.2 验证码错误
                errors.put("code", "验证码错误");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:"+DomainNameUtils.auth+"/reg.html";
            }
        }
    }

    /**
     * 登陆信息
     * @author GuLin
     * @date 22:44 2021/6/29
     * @param vo 登陆
     * @param attributes 重定向
     * @param session 会话
     * @return java.lang.String
     **/
    @PostMapping(value = "/login")
    public String login(@Valid UserLoginVo vo, BindingResult result,RedirectAttributes attributes, HttpSession session) {
        //判断校验是否通过
        Map<String, String> errors = new HashMap<>();
        if(result.hasErrors()){
          StringBuffer sbf = new StringBuffer();
          result.getFieldErrors().forEach(item->{
              sbf.append(item.getDefaultMessage()+",");
              errors.put("msg",sbf.toString());
              attributes.addFlashAttribute("errors",errors);
          });
          return "redirect:"+DomainNameUtils.auth+"/login.html";
        }
        R r = memberFeignService.login(vo);
        if(r.getCode() == 0){
            MemberResponseVo memberResponseVo = r.getData("data",new TypeReference<MemberResponseVo>(){});
            session.setAttribute(RedisConstant.LOGIN_USER,memberResponseVo);
            return "redirect:"+DomainNameUtils.index;
        } else {
            errors.put("msg",r.getData("msg",new TypeReference<String>() {}));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:"+DomainNameUtils.auth+"/login.html";
        }
    }

    /**
     * 页面跳转会话处理
     * @author GuLin
     * @date 16:50 2021/6/30
     * @param session
     * @return java.lang.String
     **/
    @GetMapping({"/login.html","/","/index","/index.html"})
    public String loginPage(HttpSession session) {
        //从session先取出来用户的信息，判断用户是否已经登录过了
        Object attribute = session.getAttribute(RedisConstant.LOGIN_USER);
        //如果用户没登录那就跳转到登录页面
        if (null==attribute) {
            return "login";
        } else {
            return "redirect:"+ DomainNameUtils.index;
        }
    }


}
